<?php
/**
 * @package Autogenerator for Joomla!
 * @version 3.0.0
 * @author Truong Cong Duc <truongcongduc4@gmail.com>
 * @link autogenerator.blogspot.com
 * @copyright (c) 2013, Truong Cong Duc
 * @license GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

class AutogeneratorTableMvc extends JTable {

    public function __construct(&$db) {
        parent::__construct('#__auto_mvc', 'id', $db);
    }

    
    public function checkTitleValid($sTitle) {
        $sRegex = '/^[A-Za-z0-9_]+$/';

        if (!preg_match($sRegex, $sTitle))
            return false;

        return true;
    }

    public function checkDuplicateTitle() {
        if ($this->table_id > 0) {
            $aMVCs = AutogeneratorHelper::getAllMVCsByTableId($this->table_id);
            
            foreach ($aMVCs as $oMVC) {
                if ($oMVC->id == $this->id)
                    continue;

                if (JString::strcmp($oMVC->title, $this->title) == 0)
                    return false;
            }

            return true;
        }

        return false;
    }

    
    public function check() {
        $this->title = trim(strtolower($this->title));
        $this->title = str_replace(' ', '_', $this->title);
        
        if (!$this->checkTitleValid($this->title)) {
            $this->setError(JText::_('COM_AUTOGENERATOR_MVC_ERROR_MESSAGE_MVC_TITLE_NOT_VALID'));
            return false;
        }

        $iFirstChar = ord($this->title[0]);
        
        // Check in [A - z].
        if (ord('A') > $iFirstChar || $iFirstChar > ord('z')) {
            $this->setError(JText::_('COM_AUTOGENERATOR_MVC_ERROR_MESSAGE_MVC_TITLE_FIRST_CHAR_NOT_VALID'));
            return false;
        }

        // Check duplicate title.
        if (!$this->checkDuplicateTitle()) {
            $this->setError(JText::_('COM_AUTOGENERATOR_MVC_ERROR_MESSAGE_MVC_TITLE_DUPLICATE'));
            return false;
        }
        
        return true;
    }

    
}
